"""
第10次作业：
下载群文件里的access.log-20191119，通过正则表达式匹配，找出文件中所有访问记录里。
访问次数最多的前10个IP，访问最频繁的前10个页面，并使用pyechart画出饼状图
"""

import re
import heapq
from pathlib import Path

from pyecharts import options as opts
from pyecharts.charts import Pie

HIGHEST_ACCESS_IP = 10
PATTERN = r'(?P<ip>[\d.]+) - - [^\]]+\] "\S+ (?P<path>\S+)'
regex = re.compile(PATTERN)


def render(src, title, output=None):
    if output is None:
        output = title
    Pie().add(
        "",
        [list(z) for z in src],
        radius=["40%", "55%"],
        label_opts=opts.LabelOpts(
            position="outside",
            formatter="{a|{a}}{abg|}\n{hr|}\n {b|{b}: }{c}  {per|{d}%}  ",
            background_color="#eee",
            border_color="#aaa",
            border_width=1,
            border_radius=4,
            rich={
                "a": {"color": "#999", "lineHeight": 22, "align": "center"},
                "abg": {
                    "backgroundColor": "#e3e3e3",
                    "width": "100%",
                    "align": "right",
                    "height": 22,
                    "borderRadius": [4, 4, 0, 0],
                },
                "hr": {
                    "borderColor": "#aaa",
                    "width": "100%",
                    "borderWidth": 0.5,
                    "height": 0,
                },
                "b": {"fontSize": 16, "lineHeight": 33},
                "per": {
                    "color": "#eee",
                    "backgroundColor": "#334455",
                    "padding": [2, 4],
                    "borderRadius": 2,
                },
            },
        ),
    ) \
        .set_global_opts(title_opts=opts.TitleOpts(title=title)) \
        .render(f"{output}.html")


def statistics(paths, encoding="utf-8"):
    res_ip = {}
    res_path = {}
    if isinstance(paths, str):
        paths = [paths]
    for path in paths:
    # 考虑这里优化下呗
        file = Path(path)
        if file.exists():
            with file.open(encoding=encoding) as f:
                for line in f:
                    match = regex.match(line) 
                    if match:
                        ip = match.groupdict()['ip']
                        http_path = match.groupdict()['path']

                        res_ip[ip] = res_ip.get(ip, 0) + 1
                        res_path[http_path] = res_path.get(http_path, 0) + 1

    result_ip = heapq.nlargest(HIGHEST_ACCESS_IP, res_ip.items(), key=lambda item: item[1])
    result_path = heapq.nlargest(HIGHEST_ACCESS_IP, res_path.items(), key=lambda item: item[1])

    render(result_ip, 'ip统计')
    render(result_path, 'path统计')


statistics(r'./access.log-20191119')

# 不错哦